var bookObject = { unsaved: false, id: 0, name: '', description: '', visibility: 'open', saveLocation: 'local', type: 'personal' };
var clonedCharts = [];

function setUp(){

	retrieveTranslations();

	bindDraggables();

	$("#cellHolder").droppable({
		accept: '.chartResult',
		activeClass: 'cellHover',
		drop: function(event, ui) { 
			$('#infoPane').remove();
			copyChart(ui.draggable, "#activeChartItemContainer");
			ui.helper.remove();
			bookObject.unsaved = true;
		}
	});
	
	$('.chartActiveResult img').removeAttr('align');
	
	$('a.chartRemove').bind('click', function(){ removeChart(this) });
	
	// Bind the save button.
	$('a#save_book').bind('click', function(){
		saveDialog();
	});	
	
	$('.chartActiveResult').bind('dblclick', function(){
		window.location = $(this).children('p').children('a').attr('href');
	});
	
	var qs = window.location.search;
	// Get the id from the request URL
	var id = qs.match(/\?.*?id=(\w+)/);
	
	// Is this a new book or a current one?
	if(id == null){
		bookObject.id = 0;
	} else {
		bookObject.id = parseInt(id[1]);	
		bookObject.name = $('#book_name').text();
	}	
	
	
	// Doubleclick handler for chart for renaming book.
	$('#book_name').bind('dblclick', function(e){
		data = $(this).text();
		
		$('#book_name').html( $("<input/>", { id: $(this).attr('id') + 'box' }).val( data ));
		
		$('#' + $(this).attr('id') + 'box').focus();
		
		$("#" + $(this).attr('id') + 'box').bind('focusout', function(e){
			data = $(this).val();
			$('#book_name').html( data );
			bookObject.name = data;
			bookObject.unsaved = true;
		});
	});	
	
	// If its a new book it'll just have a text box. Bind focusout to save back.
	$('#book_namebox').bind('focusout', function(e){
		data = $(this).val();
		$('#book_name').html( data );
		bookObject.name = data;	
		bookObject.unsaved = true;
	});
	
}

function bindDraggables(){
	$(function() {
		$(".chartResult").draggable({ 
			revert: 'invalid',
			opacity: 0.7,
			helper: 'clone',
			
			start: function() {
	        	this.style.display = "none";
	        },
	        stop: function() {
	        	this.style.display = "";
	        }
	        /*
			start: function(event, ui){
				$(this).addClass('chartActiveResult', 200);
			},
			stop: function(event,ui){
				$(this).removeClass('chartActiveResult', 200);
			},*/
		});
	});
}

function cloneChartDialog(){
	if(comittedCharts.length > 0){
		getFragment("bookCloneChartDialog", function(data) {
			jQuery.facebox(data);
			
			// Populate the option.
			$('#PBAdditionalCharts').children().remove();
			$('#PBAdditionalCharts').bind('change', function(){
				 description = comittedCharts[$(this).val()].description;
				 if(description != ""){
				 	$('#PBChartDescr').html( description );
				 } else {
				 	$('#PBChartDescr').html( "(No Description)" );
				 } 
			});
			
			for(i in comittedCharts){
				if( comittedCharts[i].chID in ato(clonedCharts) ){
				} else {
					$('#PBAdditionalCharts').append( 
						$("<option>", { value: i, text: comittedCharts[i].name }) 
					);
				}
			}
			
			$('#PBClone_Chart').bind('click', function(){

				if($('#PBAdditionalCharts').val() != null){
					data = comittedCharts[$('#PBAdditionalCharts').val()];
					cloneChart(data, "#activeChartItemContainer");
					
					// Remove option from dialog
					$("#PBAdditionalCharts > option:selected").remove();
					clonedCharts.push(data.chID);
					
					bookObject.unsaved = true;
				}
			});
			
		});
	} else {
		alert('You do not currently have any other charts to add.');
	}

}

function copyChart(source, target){
	
	removeLink = $("<a>", { 'class': 'chartRemove', 'href': '#', 'click': function(){ removeChart(this) } }).append( $("<img>", {'src' : '../images/close.png' }) );
	
	
	$(target).append( $('<div />', { 'class':"ui-corner-all chartResult chartActiveResult " + $(source).attr('class').split(' ').slice(-2,-1), id: "a" + $(source).attr('id') })
		.append( $(removeLink)).append( $(source).contents() )
		.bind('dblclick', function(){
			window.location = $(this).children('p').children('a').attr('href')
		})
	);

	// Remove the chart from the panel
	$(source).remove();
}

function cloneChart(data, target){
	removeLink = $("<a>", { 'class': 'chartRemove', 'href': '#', 'click': function(){ $(this).parent().fadeOut('slow', function() { (this).parent().remove() }) } }).append( $("<img>", {'src' : '../images/close.png' }) );
	
	$(target).append( $('<div />', { 'class':"ui-corner-all chartClone chartResult chartActiveResult userChart", id: "ach" + data.chID })
		.append( $(removeLink)).append( $("<h3>", { text: data.name }), $("<p>", { text: data.description }), $("<p>", { html: "<a href=\"chart?id=" + data.chID + "\">View Chart</a>" }) )
		.bind('dblclick', function(){
			window.location = $(this).children('p').children('a').attr('href')
		})
	);

}

function removeChart(source){
	element = $(source).parent();

	$(element).fadeOut('slow', function() {
		$(element).children('a').remove();

		$(element).switchClass('chartActiveResult', 'chartResult', 0);
		
		// Do we have groups at the side?
		if( $('#PBcharts > h3').length == 2){
			if( $(element).hasClass('groupChart') ){
				$('#PBcharts > h3:first').after( $(element).fadeIn() );
			} else {
				$('#PBcharts > h3:last').after( $(element).fadeIn() );
			}	
		} else {
			$('#chartThumbHolder').append( $(element).fadeIn() );
		}

		bookObject.unsaved = true;
		
		bindDraggables();
	});
}

function saveDialog(){
	// Check to see if we are currently saving a current book (requires no more user input), or a new book, which will require the user to confirm book info before saving.
	if(bookObject.unsaved == true){
	
		if(bookObject.name != ""){
			if(bookObject.id == 0){
				getFragment("saveBook", function(data) {
					jQuery.facebox(data);
					
					$.each(PicBoard.managedGroups, function(i, v){
						$('select#save_location').append( $("<option>", { 'val': parseInt(v[0]), 'text': v[1] }) );
					});
					
					$('#bookName').val(bookObject.name);
					$('#bookDescription').val(bookObject.description);
					
					$('#confirm_save_book').bind('click', function(){
					
						// Set data back to the book object.
						bookObject.description = $('#bookDescription').val();
						bookObject.saveLocation = $('#save_location').val();
						bookObject.visibility = $('input[type=radio][name=book_private]:checked').val();
						bookObject.name = $('#bookName').val();
						
						$('#book_namebox').val(bookObject.name).trigger('focusout');
						
						$('#book_name').text(bookObject.name);
						
						jQuery.facebox.close();
						// Fire the save event
						saveBook();
					});
					
				});
			} else {
				// Auto save & show save message
				saveBook();
			}
		} else {
			// The book MUST have a name. Notify the user.
			alert('This book does not currently have a name.');
		}
	
	}
}

function saveBook(){

	var sendData = { bookID: parseInt(bookObject.id), bookName: bookObject.name, description: bookObject.description, visibility: bookObject.visibility, type: bookObject.type, group_gID: bookObject.saveLocation, charts: [], cloneCharts: [] };

	$('.chartActiveResult').each(function(index){
		// Add the chart ID to the object
		chID = $(this).attr('id').match(/ach(\d+)/);
		
		if($(this).hasClass('chartClone')){
			sendData.cloneCharts.push( parseInt(chID[1]) );
		} else {
			sendData.charts.push( parseInt(chID[1]) );
		}
		
	});
	
	// Has the user added any charts?
	if(sendData.charts.length == 0 && sendData.cloneCharts.length == 0){
		// The user has not added anything. We should let them know that they need to add something first before saving...
		alert('Please add some charts first before saving.');
	} else {
		showMessagePane("Saving Book...", null, null);
		
		sendData = jQuery.param(sendData);
	
		// Send the data off to the server.
		$.post(PicBoard.baseURL + 'rsrc.php?req=saveBook', sendData, function(data){
			if(data.statusCode == 200){
				$("#messagePane").slideToggle();
				
				if(typeof data.payload != "undefined"){
					bookObject.id = data.payload.bookID;
				}
				bookObject.unsaved = false;
				//console.log(bookObject.unsaved);
			} else {
				jQuery.facebox(data.message);
			}
		}, 'json');
	}
	
}

function retrieveTranslations(){
	// Retrieve the language strings we are going to need.
	map = ['lang_282_unsavedWork'];
	
	PicBoard.getTranslations(map, function(){});
}

function checkForUnsavedWork(){
	if(bookObject.unsaved){
		return PicBoard.languageMap.lang_282_unsavedWork;
	} else {
		return;
	}
	
}


PicBoard.addLoadEvent( "setUp()" );
PicBoard.addLoadEvent( "$(window).bind('beforeunload', function(){ return checkForUnsavedWork(); });" );